package com.excesys.exsecs.eco.task;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.excesys.exsecs.eco.entity.EcoWeatherFlow;
import com.excesys.exsecs.eco.service.EcoWeatherFlowService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.net.URI;
import java.time.LocalDate;

@Slf4j
@Component
@AllArgsConstructor
public class WeatherTask {

    private final RestTemplate restTemplate;
    private final EcoWeatherFlowService ecoWeatherFlowService;

    private static final String API_KEY = "ec1a5ac27a095f5f954ef853b71e9c05";
    private static final String CITY = "Shanghai";
    private static final String API_URL = "http://api.openweathermap.org/data/2.5/weather?q=" + CITY + "&appid=" + API_KEY + "&units=metric";

    @Scheduled(cron = "0 0 0,12 * * ?")
    private void insertWeatherFlow() {
        ResponseEntity<JSONObject> response = restTemplate.getForEntity(API_URL, JSONObject.class);
        if (response.getStatusCode().is2xxSuccessful()) {
            JSONObject json = response.getBody();
            BigDecimal maxValue = json.getJSONObject("main").getBigDecimal("temp_max").setScale(0, BigDecimal.ROUND_HALF_UP);
            long count = ecoWeatherFlowService.count(Wrappers.<EcoWeatherFlow>lambdaQuery().eq(EcoWeatherFlow::getTimeValue, LocalDate.now()));
            if (count == 0) {
                EcoWeatherFlow ecoWeatherFlow = new EcoWeatherFlow();
                ecoWeatherFlow.setTimeValue(LocalDate.now());
                ecoWeatherFlow.setMaxValue(maxValue.floatValue());
                ecoWeatherFlowService.save(ecoWeatherFlow);
            }
        } else {
            throw new RuntimeException("Failed to retrieve user data: " + response.getStatusCode());
        }
    }
}
